mod client;

use bytes::Bytes;
use chrono::Local;
use futures::{SinkExt, StreamExt};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio_util::codec::{Framed, LengthDelimitedCodec};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>{

    let address = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "127.0.0.1:8888".to_string());

    println!("listen address: {}", address);

    // let listener = TcpListener::bind(&address).await.unwrap();

    // 使用?操作符,函数返回值需要声明为Result类型
    let listener = TcpListener::bind(&address).await?;
    println!("listening...");

    loop {
        let (stream,addr) = listener.accept().await.unwrap();
        let mut freebsd = Framed::new(stream, LengthDelimitedCodec::new());
        println!("accept from {}", addr);
        tokio::spawn(async move {
            while let Some(data) = freebsd.next().await {
                match data {
                    Ok(data) => {
                        let data = String::from_utf8(data.to_vec()).unwrap();
                        println!("recv: {}", data);
                        let res = process(&data);
                        freebsd.send(Bytes::from(res)).await.unwrap();
                    },
                    Err(e) => {
                        println!("error: {}", e);
                    }
                }

            }
        });

    }


}


fn process(s: &str) -> String {
    if s == "time" {
        return Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
    } else {
        "not found".to_string()
    }
}
